package com.gtlab1207.br_awareness.filter;

import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class ACorsFilter extends OncePerRequestFilter {

    /**
     * 跨域设置
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        String originHeader = request.getHeader("Origin");
        String[] IPs = {"http://localhost:8090","http://localhost:8525"};
        System.out.println("-----cors----"+originHeader+"----cors-----");

//        if (java.util.Arrays.asList(IPs).contains(originHeader) && request.getHeader("Access-Control-Request-Method") != null )
//        {
            response.addHeader("Access-Control-Allow-Origin", originHeader);
            response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE");
            response.addHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Origin, Access-Control-Origin, Authorization,Content-Type, Content-Range, Content-Disposition, Content-Description,Origin, X-Requested-With, sessionId");
            response.addHeader("Access-Control-Allow-Credentials", "true");
////        }

        filterChain.doFilter(request, response);
    }

}